package handler

import (
	"github.com/gin-gonic/gin"
	"im/api/request"
	"im/global"
	"im/model"
	"net/http"
)

func Show(context *gin.Context) {
	var req request.Show
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
			"data":    nil,
		})
		return
	}
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	var user []model.User
	global.DB.Where("id = ?", req.Id).First(&user)
	if req.Account != "" {
		global.DB.Offset(offset).Where("account like ?", "%"+req.Account+"%").Limit(req.Size).Find(&user)
	}
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "搜索成功",
		"data":    user,
	})
}

func List(context *gin.Context) {
	var req request.FriendList
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
			"data":    nil,
		})
		return
	}
	var friend []model.Friend
	global.DB.Order("created_at desc").Find(&friend)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查询成功",
		"data":    friend,
	})
}

func Add(context *gin.Context) {
	var req request.FriendAdd
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "获取失败",
			"data":    nil,
		})
		return
	}
	add := model.FriendAdd{
		UserId:       req.UserId,
		ToId:         req.ToId,
		Introduction: req.Introduction,
		Status:       req.Status,
	}
	global.DB.Create(&add)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "已发送好友申请",
		"data":    add.ID,
	})
}
